const fs = require('fs')

const uploadService = require("../service/uploadService")

class UploadController {
  async uploadPicture(ctx, next) {
    // console.log(1);
    const {pid} = ctx.params
    const file = ctx.req.file
    const { mimetype, filename, path } = file
    const { insertId } = await uploadService.savePicture(mimetype, filename, path,pid)
    const res = await uploadService.getPicture(insertId)
    ctx.body = {
      data: res[0],
      meta: {
        msg: '上传成功',
        status:200
      }
    }
  }
  async getPicture(ctx, next) {
    const {path} = ctx.params 
    // console.log(path);
    const reader = fs.createReadStream('uploads/picture/' + path)
    // console.log(reader);
    const res = await uploadService.getPictureByPathname(path)
    ctx.response.set('content-type', res[0].mimetype);
    ctx.body = fs.createReadStream(`uploads/picture/${path}`);
  }
}
module.exports = new UploadController()